#ifndef __FSM_H__
#define __FSM_H__

#ifdef __cplusplus
extern "C"
{
#endif

#include <stdio.h>

    typedef struct fsm_root_st fsm_root_t;
    typedef int (*fsm_run_impl)(fsm_root_t *root, void *userdata);
    typedef struct fsm_node_st
    {
        int state;
        fsm_run_impl func;
    } fsm_node_t;

    struct fsm_root_st
    {
        char exit;
        int state; // 当前执行状态
        size_t nodes_count;
        fsm_node_t *nodes;
    };

    static void fsm_run(fsm_root_t *root, void *userdata)
    {
        if (root == NULL || root->nodes == NULL || root->nodes_count == 0)
            return;

        size_t idx = 0;
        while (root->exit == 0)
        {
            for (idx = 0; idx < root->nodes_count; idx++)
            {
                if (root->state == root->nodes[idx].state)
                {
                    root->state = root->nodes[idx].func(root, userdata); // 执行状态事件
                    goto next_iteration;                                 // 执行完毕进行下一次轮训
                }
            }
            // 如果没有找到匹配的状态，则退出循环
            root->exit = -1;
            return;

        next_iteration:
            continue;
        }
    }

#ifdef __cplusplus
}
#endif

#endif // __FSM_H__
